<template>

    <div style="max-width: 800px;margin: 10px 40px" v-loading="loading">
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">返 回</el-button>
      </div>
      <br/>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="问卷名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入问卷名称" />
        </el-form-item>
        <el-form-item label="显示顺序" prop="sort">
          <el-input-number v-model="form.sort" placeholder="请输入显示顺序" />
        </el-form-item>
        <el-form-item label="问卷描述" prop="naireDesc">
          <el-input v-model="form.naireDesc" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="问卷类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择问卷类型">
            <el-option
              v-for="dict in dict.type.sys_company_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否默认">
          <el-radio-group v-model="form.isDefault">
            <el-radio
              v-for="dict in dict.type.sys_yes_no"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="问卷状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <el-divider><i class="el-icon-caret-left"></i>请在勾选问卷包含的问题<i class="el-icon-caret-right"></i></el-divider>
      <el-button
        type="primary"
        plain
        icon="el-icon-plus"
        size="mini"
        @click="selectAll"
      >全选</el-button>    <el-button
        type="primary"
        plain
        icon="el-icon-plus"
        size="mini"
        @click="resetChecked"
      >清空</el-button>
      <el-button
        type="primary"
        plain
        icon="el-icon-plus"
        size="mini"
        @click="selectReverse"
      >反选</el-button>
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
        >展开/折叠</el-button>

<!--      <el-input-->
<!--        placeholder="输入关键字进行过滤"-->
<!--        v-model="filterText" clearable style="margin: 20px">-->
<!--      </el-input>-->

      <el-tree style="width:90%"
        :data="treedata"
        show-checkbox
        :default-expand-all="isExpandAll"
        node-key="id"
        ref="tree"
        highlight-current
        :default-checked-keys="selected"
               auto-expand-parent
        :props="defaultProps"
      >

      </el-tree>
      <br/>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">返 回</el-button>
      </div>
    </div>

</template>

<style>
.transfer-footer {
  margin-left: 20px;
  padding: 6px 5px;
}
</style>

<script>

import {addNaire, getNaire, updateNaire, updatNaire} from "@/api/system/naire";
import {treelistQuestion} from "@/api/system/question"

export default {
  name: "addQuestionnaire",
  dicts:['sys_normal_disable','sys_yes_no','sys_company_type'],
  data() {

    return {
      //filterText:'',
      loading:false,
      isExpandAll:true,
      selected:[],
      treedata:[],
      defaultProps: {
        children: 'children',
        label: 'label'
      },

      form :{
        naireId: null,
        name: null,
        sort: 1,
        naireDesc: null,
        type: null,
        questions: null,
        isDefault: "0",
        status: "0",
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
      },
      rules: {
        questionnaireName: [
          { required: true, message: "问卷标题不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    document.body.ondrop = event => {
      event.preventDefault()
      event.stopPropagation()
    }

    let naireId = this.$route.query.naireId;
    console.log('naireId',naireId)
    if (naireId) {
      this.$route.meta.title = "问卷修改";
      getNaire(naireId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改问卷数据";

        this.selected=JSON.parse(this.form.questions)
      });
    } else {
      this.$route.meta.title = "添加问卷";
      this.selected=[];
    }
    this.getQuestionTreeList();

  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    getQuestionTreeList(){
      treelistQuestion().then(response=>{
        this.treedata=response.data;
        console.log('treedata',this.treedata)
      })
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.isExpandAll = !this.isExpandAll;
      console.log(' this.isExpandAll', this.isExpandAll)
      for (var i = 0; i < this.$refs.tree.store._getAllNodes().length; i++) {
        this.$refs.tree.store._getAllNodes()[i].expanded =   this.isExpandAll;
      }

    },
    resetChecked() {
      this.$refs.tree.setCheckedKeys([]);
    },
    selectAll(){
      let keys=[]
      for(let node of this.treedata){
        keys.push(node.id)
      }
      this.$refs.tree.setCheckedKeys(keys);
    },
    selectReverse(){
      let checked=this.$refs.tree.getCheckedKeys();
      let keys=[]

      for (var i = 0; i < this.$refs.tree.store._getAllNodes().length; i++) {
        let id=this.$refs.tree.store._getAllNodes()[i].id;
        if(checked.indexOf(id)==-1 && id>0)
          keys.push(id)
      }

      this.$refs.tree.setCheckedKeys(keys);
    },

    /** 提交按钮 */
    submitForm() {
      const questions = this.$refs.tree.getCheckedKeys(true)   //  利用这个方法就可以获取到子节点
      this.form.questions=JSON.stringify(questions)
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.naireId != null) {
            updateNaire(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.reset();
              this.$store.dispatch("tagsView/delView", this.$route);
              this.$router.replace({name: 'ManageQuestionnaire'})
            });
          } else {
            addNaire(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.reset();
              this.$store.dispatch("tagsView/delView", this.$route);
              this.$router.replace({name: 'ManageQuestionnaire'})
            });
          }
        }
      });
    },
    // 取消按钮
    cancel() {
      this.reset();
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.replace({name: 'ManageQuestionnaire'})
    },
    // 表单重置
    reset() {
      this.form = {
        naireId: null,
        name: null,
        sort: null,
        naireDesc: null,
        type: null,
        questions: null,
        isDefault: "0",
        status: "0",
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
  }
};
</script>
